<template>
  <div class="container cart-cont">
    <div class="text-align-c flex flex-center step-bar-auth pad-t-12 pad-b-8">
      <ul class="auth-t-line-bar font-12">
        <li :class="stepLineOne ? 'actived' : ''">
          <div class="flex flex-center">
            <div class="circle font-13 flex flex-center"><span>1</span></div>
          </div>          
          <div class="line-t pad-t-5">绑定手机号</div>
        </li>
        <li :class="stepLineTwo ? 'actived' : ''">
          <div class="flex flex-center">
            <div class="circle font-13 flex flex-center"><span>2</span></div>
          </div>
          <div class="line-t pad-t-5">实名认证</div>
        </li>
        <li :class="stepLineThree ? 'actived' : ''">
          <div class="flex flex-center">
            <div class="circle font-13 flex flex-center"><span>3</span></div>
          </div>
          <div class="line-t pad-t-5">电子协议签约</div>
        </li>
        <li :class="stepLineFour ? 'actived' : ''">
          <div class="flex flex-center">
            <div class="circle font-13 flex flex-center"><span>4</span></div>
          </div>
          <div class="line-t pad-t-5">绑定银行卡</div>
        </li>
      </ul>
    </div>
    <div class="clear_both"></div>
    <!-- step 1, 绑定手机号 -->
    <div v-if="memberInfo && step === 1" class="panel panel-box bind-panel pad-l-15 pad-r-15">
      <div class="flex v-align-c div-input font-16 font-color-6 pad-t-14 pad-b-16">
        <div class="font-w">绑定手机</div>
        <div class="flex-item text-align-r">
          <input v-model="memberInfo.phone" maxlength="11" type="number" placeholder-class="phcolor" placeholder="请输入手机号"/>
        </div>
      </div>
      <div class="flex v-align-c div-input font-16 font-color-6 pad-t-14 pad-b-16">
        <div class="font-w">验证码</div>
        <div class="flex-item text-align-r v-align-c">
          <div class="flex-item mar-r-7">
            <input v-model="memberInfo.verificationCode" maxlength="6" type="number" placeholder-class="phcolor" placeholder="请输入验证码"/>
          </div>
          <div
            @click="sendVerificationCode"
            :class="codeBtnDisable ? 'disable' : ''"
            class="short-b-s flex flex-center width-100 height-30 font-13">
            <span>{{ codeBtnTxt }}</span>
          </div>
        </div>
      </div>
      <div v-if="showCountDown">
        <van-count-down
          use-slot
          @change="onChangeTimer"
          :time="endCountDate"
          format="ss"
          @finish="bizFinished" />
      </div>
      <div class="height-60"></div>
      <div class="submit-btn two-btn flex v-align-c">
        <div @click="$pt.navigateBack({ delta: -1 })" class="p-button flex flex-center"><span>返回</span></div>
        <div @click="nextStep(2)" class="p-button flex flex-center"><span>下一步</span></div>
        <!-- <div @click="unbindPhone" class="p-button flex flex-center"><span>解绑</span></div> -->
      </div>
    </div>
    <!-- step 2, 实名认证 -->
    <div v-if="memberInfo && step === 2" class="panel panel-box bind-panel pad-l-15 pad-r-15">
      <div class="flex v-align-c div-input font-16 font-color-6 pad-t-14 pad-b-16">
        <div class="font-w">真实姓名</div>
        <div class="flex-item text-align-r">
          <input v-model="memberInfo.name" maxlength="15" placeholder-class="phcolor" placeholder="请输入真实姓名"/>
        </div>
      </div>
      <div class="flex v-align-c div-input font-16 font-color-6 pad-t-14 pad-b-16">
        <div class="font-w">证件类型</div>
        <div class="flex-item text-align-r">身份证</div>
      </div>
      <div class="flex v-align-c div-input font-16 font-color-6 pad-t-14 pad-b-16">
        <div class="font-w">证件号码</div>
        <div class="flex-item text-align-r">
          <input v-model="memberInfo.identityCardNo" maxlength="18" type="idcard" placeholder-class="phcolor" placeholder="请输入证件号码"/>
        </div>
      </div>
      <div class="height-76"></div>
      <div class="submit-btn">
        <div @click="nextStep(3)" class="p-button flex flex-center"><span>下一步</span></div>
      </div>
    </div>
    <!-- step 3, 电子协议签约 -->
    <div v-if="memberInfo && step === 3" class="panel panel-box bind-panel pad-l-15 pad-r-15">
      <div class="height-80"></div>
      <div class="flex flex-center">
        <img
          v-if="fileSpace"
          :src="fileSpace + '/images/sign-auth-bg.png'"
          alt=""
          class="width-240 height-152">
      </div>
      <div class="font-14 font-color-9 text-align-c pad-t-15 pad-l-15 pad-r-15">根据国家法律法规和保障您个人隐身安全请先完成个人电子签约才能填写绑定银行卡</div>
      <div class="height-40"></div>
      <div class="submit-btn">
        <div
          @click="signPage"
          class="p-button flex flex-center"><span>立即签约</span></div>
      </div>
    </div>
    <!-- step 4, 绑定银行卡 -->
    <div v-if="memberInfo && step === 4" class="panel panel-box bind-panel pad-l-15 pad-r-15">
      <div class="flex v-align-c div-input font-16 font-color-6 pad-t-14 pad-b-16">
        <div class="font-w">银行卡号</div>
        <div class="flex-item text-align-r">
          <input v-model="memberInfo.card" maxlength="19" type="number" placeholder-class="phcolor" placeholder="请输入银行卡号"/>
        </div>
      </div>
      <div class="font-color-9 font-12 pad-t-6">提示：银行卡必须与实名信息是同人银行卡，并且真实有效。</div>
      <div class="height-173"></div>
      <div class="submit-btn">
        <div @click="saveBindInfo" class="p-button flex flex-center"><span>完成</span></div>
      </div>
    </div>    
    <!-- 选择证件类型列表 -->
    <van-popup
      :show="isShowTypePicker"
      position="bottom"
      @close="onTypeClose">
      <van-picker
        show-toolbar
        :columns="pickerTypeArray"
        @cancel="onTypeClose"
        @confirm="onTypeConfirm"/>
    </van-popup>
  </div>
</template>

<script>
  import {
    getMemberInfo,
    sendVerificationCode,
    bindPhone,
    unbindPhone,
    signContract,
    setRealName,
    applyBindBankCard
  } from '@/api/pay'

  export default {
    components: { },
    data() {
      return {
        step: null,
        stepLineOne: false,
        stepLineTwo: false,
        stepLineThree: false,
        stepLineFour: false,
        memberInfo: {
          name: '',
          certificateType: '',
          identityCardNo: '',
          phone: '',
          card: '',
          signContract: '',
          verificationCode: ''
        },
        isShowTypePicker: false,
        pickerTypeArray: [{
          text: '身份证',
          value: 1
        }, {
          text: '军官证',
          value: 2
        }, {
          text: '护照',
          value: 3
        }, {
          text: '其他',
          value: 99
        }],
        pickTypeId: null,
        pickTypeText: '',
        urlWeb: '',
        serverDate: '',
        endCountDate: null,
        codeBtnTxt: '获取验证码',
        codeBtnDisable: false,
        timerDown: 60000,
        bindResPhone: false,
        timeOver: null,
        showCountDown: false
      }
    },
    onLoad(options) {
      // 初始化data
      Object.assign(this.$data, this.$options.data())
    },
    onHide() {
      if (this.serverDate) {
        let startDate = new Date(this.serverDate).getTime()
        this.$pt.setStorageSync('startDate', startDate)
      }
    },
    onUnload() {
      if (this.serverDate) {
        let startDate = new Date(this.serverDate).getTime()
        this.$pt.setStorageSync('startDate', startDate)
      }
    },
    mounted() {
      this.getMemberInfo()
    },
    methods: {
      async nextStep(step) {
        if (this.checkStep(step)) return
        if (Number(step) === 2) {
          await this.bindPhone()
          if (this.bindResPhone) {
            this.step = 1
            return
          }
        }
        if (Number(step) === 3) {
          this.setRealName()
        }
        this.step = Number(step)
        this.changeStep(Number(step))
      },
      checkStep(step) {
        let resVal = false
        if (Number(step) === 2) {
          if (!this.memberInfo.phone) {
            this.$utils.showToast({ title: '请填写手机号码' })
            resVal = true
            return resVal
          }
          // if (!(/^1\d{10}$/.test(this.memberInfo.phone))) {
          //   this.$utils.showToast({ title: '请填写正确的手机号！' })
          //   resVal = true
          //   return resVal
          // }
          if (!this.memberInfo.verificationCode) {
            this.$utils.showToast({ title: '请填写验证码' })
            resVal = true
            return resVal
          }
        }
        if (Number(step) === 3) {
          if (!this.memberInfo.name) {
            this.$utils.showToast({ title: '真实姓名不能为空' })
            resVal = true
            return resVal
          }
          if (!this.memberInfo.identityCardNo) {
            this.$utils.showToast({ title: '证件号不能为空' })
            resVal = true
            return resVal
          }
          if (!this.$utils.checkUserIdCode(this.memberInfo.identityCardNo)) {
            this.$utils.showToast({ title: '请输入正确的证件号' })
            resVal = true
            return resVal
          }
        }
      },
      changeStep(step) {
        // 逻辑处理
        if (step === 1) {
          this.$pt.setNavigationBarTitle({
            title: '绑定手机'
          })
        } else {
          this.$pt.setNavigationBarTitle({
            title: '实名认证'
          })
        }
        if (this.memberInfo.certificateType && step === 2) {
          this.pickTypeId = this.memberInfo.certificateType
          this.pickerTypeArray.forEach(item => {
            if (item.value === this.memberInfo.certificateType) {
              this.pickTypeText = item.text
            }
          })
        }
        switch (step) {
          case 1:
            this.stepLineOne = true
            this.stepLineTwo = false
            this.stepLineThree = false
            this.stepLineFour = false
            break
          case 2:
            this.stepLineOne = true
            this.stepLineTwo = true
            this.stepLineThree = false
            this.stepLineFour = false
            break
          case 3:
            this.stepLineOne = true
            this.stepLineTwo = true
            this.stepLineThree = true
            this.stepLineFour = false
            break
          case 4:
            this.stepLineOne = true
            this.stepLineTwo = true
            this.stepLineThree = true
            this.stepLineFour = true
            break
        }
        if (step === 3) {
          this.urlWeb = 'https://www.veekray.com'
        }
      },
      onTypeClose() {
        this.isShowTypePicker = false
      },
      onTypeConfirm(e) {
        this.isShowTypePicker = false
        this.pickTypeId = e.mp.detail.value.value
        this.pickTypeText = e.mp.detail.value.text
        this.memberInfo.certificateType = this.pickTypeId
      },
      getMemberInfo() {
        getMemberInfo(this.getCustomerId).then((response) => {
          // '售后单包含售后进行中的商品,请等待该件商品售后流程结束,或者发起其他商品售后'
          if (response.isError) return
          if (this.step === 1 && this.$pt.getStorageSync('startDate')) {
            let nowDate = new Date(response.date).getTime()
            let startDate = new Date(this.$pt.getStorageSync('startDate')).getTime()
            let crossDate = null
            // 进过时间戳，当前时间戳 - 开始时得时间戳
            crossDate = nowDate - startDate
            // console.log('backDate', crossDate)
            if (crossDate < this.timerDown) {
              this.endCountDate = this.timerDown - crossDate
            } else {
              this.codeBtnTxt = '获取验证码'
              this.codeBtnDisable = false
            }
          }
          // response.data.phone = '18876316098'
          // response.data.name = ''
          // response.data.identityCardNo = ''
          // response.data.contractNo = ''
          this.memberInfo = response.data
          // this.step = 1
          if (!this.memberInfo.phone) {
            this.step = 1
            this.changeStep(this.step)
            return
          }
          if (this.memberInfo.phone) {
            this.step = 2
          }
          if (this.memberInfo.name && this.memberInfo.identityCardNo) {
            this.step = 3
          }
          if (this.memberInfo.contractNo) {
            this.$pt.hideToast()
            clearInterval(this.timeOver)
            this.step = 4
          }
          this.changeStep(this.step)
        }).catch(() => {
        })
      },
      onChangeTimer(e) {
        let timer = e.mp.detail
        this.codeBtnTxt = timer.seconds + 's后重新获取'
        this.codeBtnDisable = true
        // console.log('timer 111', this.codeBtnTxt)
      },
      bizFinished() {
        this.$pt.removeStorageSync('startDate')
        this.codeBtnTxt = '获取验证码'
        this.codeBtnDisable = false
        this.showCountDown = false
        // console.log('bizFinished 111')
      },
      // 获取手机验证码
      sendVerificationCode() {
        if (!this.memberInfo.phone) {
          this.$utils.showToast({ title: '请填写手机号码' })
          return
        }
        // verificationCodeType 9-绑定手机，6-解绑手机
        if (this.codeBtnDisable) return
        this.showCountDown = true
        this.endCountDate = this.timerDown
        sendVerificationCode({
          memberId: this.getCustomerId,
          phone: this.memberInfo.phone,
          verificationCodeType: 9
        }).then((response) => {
          if (response.isError) return
          this.serverDate = response.date
        }).catch(() => {
        })
      },
      // 绑定手机号码
      bindPhone() {
        return new Promise((resolve, reject) => {
          bindPhone({
            memberId: this.getCustomerId,
            phone: this.memberInfo.phone,
            verificationCode: this.memberInfo.verificationCode
          }).then((response) => {
            if (response.isError) {
              this.bindResPhone = true
              return
            }
            this.bindResPhone = false
            resolve(true)
          }).catch(() => {
          })
        })
      },
      // 解绑手机号码
      unbindPhone() {
        unbindPhone({
          memberId: this.getCustomerId,
          phone: this.memberInfo.phone,
          verificationCode: this.memberInfo.verificationCode
        }).then((response) => {
          if (response.isError) return
          console.log('')
        }).catch(() => {
        })
      },
      setRealName() {
        setRealName({
          memberId: this.getCustomerId,
          name: this.memberInfo.name,
          identityNo: this.memberInfo.identityCardNo
        }).then((response) => {
          if (response.isError) return
          console.log('')
        }).catch(() => {
        })
      },
      signPage() {
        signContract({
          memberId: this.getCustomerId
        }).then((response) => {
          if (response.isError) return
          this.signUrl = response.data
          let that = this
          this.$pt.navigateToMiniProgram({
            appId: 'wxc46c6d2eed27ca0a',
            path: 'pages/merchantAddress/merchantAddress',
            extraData: {
              targetUrl: that.signUrl
            },
            envVersion: 'release',
            success(res) {
              // 打开成功
              console.log('打开成功小程序 111')
              that.$utils.showToast({
                title: '签约处理中',
                icon: 'loading',
                duration: 10000,
                mask: true
              })
              // 定时调用  判断是否已签约
              that.timeOver = setInterval(() => {
                that.getMemberInfo()
              }, 1500)
            }
          })
        }).catch(() => {
        })
      },
      applyBindBankCard() {
        applyBindBankCard({
          memberId: this.getCustomerId,
          cardNo: this.memberInfo.card,
          phone: this.memberInfo.phone
        }).then((response) => {
          if (response.isError) return
          this.$utils.showToast({ title: '银行卡绑定成功！' })
          setTimeout(() => {
            this.$pt.navigateTo({url: '/pages/personal/verify-auth/allin-auth/main'})
          }, 700)
        }).catch(() => {
        })
      },
      saveBindInfo() {
        // 保存数据
        if (!this.memberInfo.card) {
          this.$utils.showToast({ title: '请填写银行卡号' })
          return
        }
        if (this.memberInfo.card.length < 16) {
          this.$utils.showToast({ title: '请填写正确的银行卡号！' })
          return
        }
        this.applyBindBankCard()
      }
    }
  }
</script>

<style lang="less" scoped>
  .container{
    background: #fff;
    min-height: calc(100vh);
  }
  .scroll-main{
    .submit-btn{
      position: fixed;
      left: 0;
      bottom: 0;
      width: 100%;
      padding: 10px 15px!important;
      .p-button{
        height: 35px;
        font-size: 16px;
      }
    }
  }
  .step-bar-auth{
    background: #f5f5f5;
  }
  .auth-t-line-bar{
    margin: 0;
    padding: 0;
    &:after{
      content: '';
      display: block;
      clear: both;
      font-size: 0;
    }
    li{
      list-style: none;
      margin: 0;
      padding: 0;
      width: 90px;
      text-align: center;
      color: #999;
      float: left;
      position: relative;
      &:before{
        content: '';
        display: block;
        width: 150%;
        height: 2px;
        background: #dbdbdb;
        position: absolute;
        left: -50%;
        top: 7px;
        z-index: 1;
      }
      &.actived{
        color: #333;
        &:before{
          content: '';
          display: block;
          background: #ffe100;
        }
        .circle{
          background: #ffe100;
          color: #333;          
        }
      }
      &:first-child{
        &:before{
          content: '';
          display: none;
        }
        &.actived{
          &:before{
            content: '';
            display: none;
          }
        }
      }
      &:last-child{
        &:before{
          content: '';
          display: block;
          width: 100%;
        }
      }
      .circle{
        background: #dbdbdb;
        color: #fff;
        width: 16px;
        height: 16px;
        border-radius: 100px;
        position: relative;
        z-index: 5;
      }
    }
  }
  .short-b-s{
    background: #ffe100;
    color: #333333;
    border-radius: 8px;
    &.disable{
      background: #dbdbdb;
      color: #666666;
    }
  }
  .status-bar{
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    z-index: 30;
    text-align: center;
    padding: 1px 0 3px 0;
    h2{
      font-size: 15px;
      font-weight: normal;
      margin: 0;
      padding: 0;
    }
    p{
      font-size: 12px;
      margin-top: -3px;
    }
    &.status-1{
      background: #818181;
      color: #fff;
    }
    &.status-2{
      background: #04c160;
      color: #fff;
    }
    &.status-3{
      background: #ff4a4a;
      color: #fff;
    }
  }
  .disabledRead{
    opacity: 0.5;
  }
  .select-bar{
    border: #9e9e9e 1px solid;
    padding: 4px 8px;
    color: #818181;
    .icon-arrow-right{
      color: #9e9e9e;
      transform:rotate(90deg);
    }
  }
  .select-local{
    border: #9e9e9e 1px solid;
    border-radius: 100px;
    padding: 5px 6px;
    label{
      font-size: 10px;
      color: #9e9e9e;
      display: block;
      width: 45px;
      margin-left: 5px;
    }
  }
  .submit-btn{
    padding: 0 66px;
    box-sizing: border-box;
    background: #fff;
    &.two-btn{
      padding: 0 15px;
      .p-button{
        width: 166px;
        // display: inline-block;
        // vertical-align: middle;        
        &:first-child{
          border: #FFE200 1px solid;
          background: #fffce7;
          margin-right: 12px;
        }
      }
    }
    .p-button{
      border-radius: 100px;
      height: 45px;
      font-size: 19px;
      color: #333333;
      font-weight: bold;
      border: none;
      border: #ffe200 1px solid;
      background: #ffe200;
      &[disabled]{
        color: #595959;
        background: linear-gradient(to right, #dadada, #dadada);
      }
      &:after{
        content: '';
        display: none;
      }
    }
  }
  .address-textarea {
    width: 100%;
    line-height: 1.2;
    height: 40px;
  }
  .upload-bar{
    text-align: center;
    width: 140px;
    height: 80px;
    border-radius: 5px;
    box-sizing: border-box;
    border: #aeaeae 1px dashed;
    img{
      display: inline-block;
    }
    label{
      display: block;
      font-size: 12px;
      color: #595959;
      margin-top: -4px;
    }
  }
  .border-b{
    border-bottom: #f1f1f1 1px solid;
  }
  .panel-box{
    border-radius: 0px;
    box-shadow: none;
    border-top: none;
    border-bottom: none;
    margin-left: 0;
    margin-right: 0;
  }  
  .tips-t{
    color: #fff;
    font-size: 12px;
    background: #ff4144;
  }
  .s-input-bar{
    // border: #c5c5c5 1px solid;
    // border-radius: 8px;
    font-size: 12px;
    padding: 0 0 0 8px;
    overflow: hidden;
    input{
      width: 70%!important;
    }
    .per-span{
      text-align: right;
      display: block;
      height: 30px;
      line-height: 30px!important;
      padding: 0 8px 0 0;
      margin-right: 0px;
    }
  }
  .tips-content{
    line-height: 1.8;
  }
  .font-gray{
    color: #999999!important;
  }
  .panel-box{
    h2{
      &:before{
        content: '';
        display: inline-block;
        vertical-align: top;
        width: 5px;
        height: 15px;
        background: #f8c400;
        margin: 3px 10px 0 6px;
      }
    }
  }
  .setting input {
    width: 100%;
  }
  .setting textarea {
    width: 100%;
    height: 100px;
  }
  .div-input {
    border-bottom: #f5f5f5 1px solid;
  }
  // .div-input:last-child {
  //   border-bottom: 0;
  // }
</style>
